import os
from typing import List, Dict, Any
from config.settings import settings


def list_source_files(directory: str, extensions: List[str] = None) -> List[str]:
    """列出指定目录下的所有源文件
    
    Args:
        directory: 要扫描的目录路径
        extensions: 文件扩展名列表，默认为settings.C_FILE_EXTENSIONS
        
    Returns:
        源文件路径列表
    """
    if extensions is None:
        extensions = settings.C_FILE_EXTENSIONS

    source_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if any(file.endswith(ext) for ext in extensions):
                source_files.append(os.path.join(root, file))
    return source_files


class CodeSegment:
    """代码片段类"""

    def __init__(self, name: str, content: str, start_line: int, end_line: int):
        self.name = name
        self.content = content
        self.start_line = start_line
        self.end_line = end_line


def split_c_file(content: str) -> List[CodeSegment]:
    """将C文件内容分割成代码片段
    
    Args:
        content: 文件内容
        
    Returns:
        代码片段列表
    """
    segments = []
    lines = content.split('\n')
    current_segment = []
    current_name = None
    start_line = 1
    line_count = 0

    for line in lines:
        line_count += 1
        line = line.strip()

        # 跳过空行和注释
        if not line or line.startswith('//') or line.startswith('/*'):
            continue

        # 检查是否是函数定义
        if line.endswith('{'):
            if current_segment:
                # 保存当前片段
                segments.append(CodeSegment(
                    name=current_name or f"block_{start_line}_{line_count - 1}",
                    content='\n'.join(current_segment),
                    start_line=start_line,
                    end_line=line_count - 1
                ))
            # 开始新片段
            current_segment = [line]
            current_name = line.split('(')[0].strip().split()[-1]  # 提取函数名
            start_line = line_count
        else:
            current_segment.append(line)

    # 保存最后一个片段
    if current_segment:
        segments.append(CodeSegment(
            name=current_name or f"block_{start_line}_{line_count}",
            content='\n'.join(current_segment),
            start_line=start_line,
            end_line=line_count
        ))

    return segments
